package commonwebgroup.commonwebartifact.util;

import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author: wuxin0011
 * @Description: 请求封装对象
 */
public final class R extends HashMap<String, Object> {

    private final static String CODE = "status";
    private final static String CODE_VALUE = "Value";
    private final static String MESSAGE = "msg";
    private final static String DATA = "response";
    private final static String SUCCESS = "success";

    public final static Integer HTTP_SUCCESS_CODE = HttpURLConnection.HTTP_OK;
    public final static Integer HTTP_ERROR_CODE = HttpURLConnection.HTTP_INTERNAL_ERROR;

    private R() {

    }

    private R(Integer code, String message, Object data) {
        this(code, message, data, false);
    }


    private R(Integer code, String message, Object data, boolean isSuccess) {
        this.put(CODE, code).put(MESSAGE, message).put(DATA, data).put(SUCCESS, isSuccess);
    }


    // 成功请求
    public static R ok(Object data) {
        return ok("响应成功！", data);
    }

    // 成功请求
    public static R ok(String message, Object data) {
        return create(HTTP_SUCCESS_CODE, message, data, true);
    }

    // 错误请求
    public static R error(Integer code, String message) {
        return create(code, message, null, false);
    }


    // 创建实例
    public static R create(Integer code, String message, Object data, boolean isSuccess) {
        return new R(code, message, data, isSuccess);
    }


    /**
     * 构造返回结果
     *
     * @param result result
     * @param error  错误信息
     * @return R
     */
    public static R getResult(Object result, AtomicReference<String> error) {
        return result == null || (error != null && error.get() != null) ? R.error(HTTP_ERROR_CODE, error == null || StringUtil.isEmpty(error.get()) ? "未知错误" : error.get()) : R.ok(result);
    }

    /**
     * 是否是ok
     *
     * @param r R
     * @return boolean
     */
    public static boolean isOk(R r) {
        return r != null && (r.get(CODE).equals(HTTP_SUCCESS_CODE) || r.get(SUCCESS).equals(true));
    }


    // 链式操作
    @Override
    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}
